package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model,QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "role/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null && !id.equals("")) {
            roleService.delete(id);
        }
        return "redirect:/role/list";  //返回的是上面查询所偶有所的方法
    }

    @RequestMapping("/input")
    public String input(Long id, Model model) {
        //遍历权限
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions", permissions);

        if (id != null) {
            //编辑
            //根据id 查询角色信息
            Role role = roleService.get(id);
            model.addAttribute("role", role);
            //遍历角色已获得的权限
            List<Permission> rolePermissions = roleService.selRolePermission(id);
            model.addAttribute("rolePermissions", rolePermissions);
        }
        return "role/input";

    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] permissionIds) {

        roleService.save(role, permissionIds);
//        if (id != null && !id.equals("")) {
//            roleService.update(role);
//        }else {
//            roleService.save(role);
//        }
        return "redirect:/role/list";
    }

}
